<template>
  <div class="car">
    <div class="header">
      <h3>购物车</h3>
    </div>
    <div class="content" v-if="isHasGoods">
      <div class="title">
        <span>购物车</span>
      </div>
      <div class="goods_msg" v-for="(item, index) in message" :key="index">
        <div class="check_box">
          <input
            type="checkbox"
            :checked="item.checked"
            @click="stateChange(index)"
          />
        </div>
        <div class="msg_img">
          <img
            :src="
              item.goods_small_logo
                ? item.goods_small_logo
                : 'http://image2.suning.cn/uimg/b2c/newcatentries/0070078057-000000000634917020_1_400x400.jpg'
            "
          />
        </div>
        <div class="msg_sec">
          <span class="msg_sec_name">{{ item.goods_name | cutName() }}</span>
          <br />
          <br />
          <span class="msg_price">￥{{ item.goods_price }}</span>
          <div class="msg_num">
            <span class="num_change" @click="numberChange('+', index)">+</span
            >&nbsp <span>{{ item.num }}</span
            >&nbsp
            <span class="num_change" @click="numberChange('-', index)">-</span>
          </div>
        </div>
      </div>
    </div>
    <div class="no_good" v-else>
      <img
        src="https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1600846893&di=72ad4fc81a7ece6e4edcd7bd43f3c1a8&src=http://hbimg.b0.upaiyun.com/e1b1467beea0a9c7d6a56b32bac6d7e5dcd914f7c3e6-YTwUd6_fw658"
      />
      <h1>这里啥也没有</h1>
    </div>
    <br /><br /><br /><br /><br /><br />
    <div class="bottomer">
      <div class="bot_checkbox">
        <input
          type="checkbox"
          :checked="isAllChecked"
          @click="checkAll()"
        />&nbsp
        <span class="all_checked">全选</span>
      </div>
      <div class="bot_right">
        <div class="bot_right_price">
          <span>合计:</span>
          <span>￥{{ allPrice }}</span>
          <span class="bg_price">包含运费</span>
        </div>
        <div class="bot_right_buy" @click="pay()">
          <span>结算({{ goodsNum }})</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      message: [],
      //全选
      isAllChecked: false,
      //是否有商品
      isHasGoods: false,
    };
  },
  created() {
    this.getMessage();
  },
  methods: {
    getMessage() {
      var goods = JSON.parse(localStorage.getItem("goods")) || [];
      this.message = goods;
      //判断购物车是否加入了商品
      if (this.message.length == 0) {
        this.isHasGoods = false;
        this.isAllChecked = false;
      } else this.isHasGoods = true;
    },
    checkAll() {
      this.isAllChecked = !this.isAllChecked;
      this.message.forEach((v) => {
        v.checked = this.isAllChecked;
      });
      //数据改变后重新存储到数据库中
      localStorage.setItem("goods", JSON.stringify(this.message));
    },
    //商品状态改变
    stateChange(index) {
      var goods = JSON.parse(localStorage.getItem("goods"));
      goods[index].checked = !goods[index].checked;
      //数据刷新
      this.message = goods;
      //把数据重新存储到本地存储中
      localStorage.setItem("goods", JSON.stringify(goods));
    },
    //数量改变
    numberChange(way, index) {
      if (way == "+") {
        this.message[index].num++;
      } else {
        if (this.message[index].num == 1) {
          this.$confirm("是否删除商品, 是否继续?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
            center: true,
          })
            .then(() => {
              this.message.splice(index, 1);
              if (this.message.length == 0) {
                this.isHasGoods = false;
              }
              //把数据重新存储到本地存储中
              localStorage.setItem("goods", JSON.stringify(this.message));
              this.$message({
                type: "success",
                message: "删除成功!",
                duration: 1000,
              });
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消删除",
                duration: 1000,
              });
            });
        } else {
          this.message[index].num--;
        }
      }
      //修改后把数据重新存储到本地存储中
      localStorage.setItem("goods", JSON.stringify(this.message));
    },
    //付钱
    pay() {
      var num = 0;
      //判断是否有被选中的商品
      this.message.forEach((v) => {
        if (v.checked) {
          num++;
        }
      });
      if (num == 0) {
        this.$message("还没有商品被选中");
      } else {
        //判断用户是否已经登陆
        var cookie = JSON.parse(localStorage.getItem("cookie"));
        if (!cookie) {
          this.$message("您还没有登陆");
          this.$router.push("/log");
        } else {
          this.$confirm(
            // "检测到未保存的内容，是否在离开页面前保存修改？",
            "确认支付",
            {
              distinguishCancelAndClose: true,
              confirmButtonText: "确定支付",
              cancelButtonText: "取消支付",
              center: true,
            }
          )
            .then(() => {
              var arr = [];
              this.message.forEach((v) => {
                if (!v.checked) {
                  arr.push(v);
                }
              });
              this.message = arr;
              //修改后把数据重新存储到本地存储中
              localStorage.setItem("goods", JSON.stringify(this.message));
              this.$message({
                type: "info",
                message: "支付成功",
                duration: 500,
              });
            })
            .catch((action) => {
              this.$message({
                type: "info",
                message: action === "cancel" ? "取消支付" : "停留在当前页面",
                duration: 500,
              });
            });
        }
      }
    },
  },
  filters: {
    cutName(val) {
      if (val.length >= 30) {
        return val.substring(0, 30) + "...";
      } else {
        return val;
      }
    },
  },
  computed: {
    goodsNum() {
      if (this.message.length == 0) {
        return 0;
      } else {
        var num = 0;
        this.message.forEach((v) => {
          if (v.checked) {
            num += v.num;
          }
        });
        return num;
      }
    },
    allPrice() {
      //假定全选为真，后期判断来改变
      this.isAllChecked = true;
      if (this.message.length == 0) {
        this.isAllChecked = false;
        return;
      } else {
        var allPrice = 0;
        this.message.forEach((v) => {
          if (v.checked) {
            allPrice += v.num * v.goods_price;
          } else {
            //如果存在没有被选定的商品
            this.isAllChecked = false;
          }
        });
        return allPrice;
      }
    },
  },
};
</script>

<style scoped>
.header {
  width: 100%;
  height: 80px;
  background-color: rgb(226, 73, 73);
  text-align: center;
  line-height: 80px;
  font-size: 16px;
}
/* 购物车为空 */
.no_good {
  width: 100;
  height: 300px;
  text-align: center;
}
.no_good img {
  width: 100%;
}
.no_good h1 {
  color: rgb(196, 191, 191);
  font-size: 16px;
}
.content .title {
  margin-top: 10px;
  width: 100%;
  height: 30px;
  line-height: 30px;
  padding: 5px 0;
  border-top: 1px solid rgb(235, 92, 92);
  border-bottom: 1px solid rgb(235, 92, 92);
  font-size: 16px;
}
.content .title span {
  padding-left: 5px;
}
.goods_msg {
  display: flex;
  width: 100%;
  height: 100px;
  border-bottom: 1px solid rgb(158, 156, 156);
  font-size: 16px;
}
.check_box {
  padding-left: 5px;
  line-height: 100px;
  flex: 1;
}
.check_box input {
  display: inline-block;
  width: 20px;
  height: 20px;
}
.msg_img {
  line-height: 100px;
  flex: 2;
}
.msg_img img {
  width: 100%;
}
.msg_sec {
  padding-left: 5px;
  flex: 5;
}
.msg_sec_name {
  display: inline-block;
  height: 42px;
}
.msg_price {
  color: red;
  float: left;
}
.msg_num {
  float: right;
}
.num_change {
  display: inline-block;
  width: 20px;
  height: 20px;
  border: 1px solid rgb(173, 166, 166);
  text-align: center;
  line-height: 20px;
}
.bottomer {
  width: 100%;
  height: 50px;
  border-top: 1px solid rgb(177, 167, 167);
  border-bottom: 1px solid rgb(177, 167, 167);
  position: fixed;
  bottom: 60px;
  display: flex;
  background-color: white;
}
.bot_checkbox {
  flex: 1;
  padding-left: 5px;
  line-height: 50px;
}
.bot_checkbox input {
  display: inline-block;
  width: 20px;
  height: 20px;
  padding-right: 5px;
}
.bot_right {
  flex: 1;
  display: flex;
}
.bot_right_price {
  width: 50%;
  height: 100%;
  background-color: rgb(236, 215, 93);
  font-size: 14px;
}
.bot_right_buy {
  width: 50%;
  height: 100%;
  background-color: rgb(235, 92, 92);
  text-align: center;
  line-height: 50px;
  font-size: 16px;
}
.bg_price {
  display: inline-block;
  padding-top: 5px;
  color: red;
}
</style>